//
//  MainActivityViewController.m
//  SocialEngine
//
//  Created by Tan NguyenBa on 9/8/12.
//  Copyright (c) 2012 Home. All rights reserved.
//

#import "MainActivityViewController.h"
#import "ActivitiesViewController.h"
#import "LoginState.h"
#import "defines.h"

@implementation MainActivityViewController
{
    LoginState *loginState;
    NSInteger iCurrentView;
    NSInteger iStateView;
    
    UITapGestureRecognizer *singleTap;
    NSInteger xPosTouch;
    BOOL isDraging;
    NSInteger iCurrentDragPos;
}

@synthesize viewMainView;
@synthesize viewMainContent;
@synthesize headerView;
@synthesize viewLeftPanel;
@synthesize btnLeftPanel;

@synthesize viewActivity;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (void) setUserInfo:(LoginState *) _loginState
{
    loginState = _loginState;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


-(void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation) fromInterfaceOrientation 
{   
    NSInteger iCurrentMainViewXPosition = 0;
    if (iStateView == MAINVIEW_SHOW_LEFTPANEL) {
        iCurrentMainViewXPosition = LEFTPANEL_WIDTH;
    }
    else if (iStateView == MAINVIEW_SHOW_LEFTPANEL_FULL) {
        iCurrentMainViewXPosition = [self.view bounds].size.width;
    }
    viewMainView.frame = CGRectMake(iCurrentMainViewXPosition, 
                                    0, 
                                    [self.view bounds].size.width, 
                                    [self.view bounds].size.height);
    NSLog(@"Content :%f", viewMainContent.frame.size.height);
    NSLog(@"Sub : %f", viewActivity.view.frame.size.height);
    
    NSInteger iCurrentLeftPanelViewWidth = [self.view bounds].size.width;
    if (iStateView != MAINVIEW_SHOW_LEFTPANEL_FULL) {
        iCurrentLeftPanelViewWidth = LEFTPANEL_WIDTH;
    }
    viewLeftPanel.frame = CGRectMake(0, 
                                    0, 
                                    iCurrentLeftPanelViewWidth, 
                                    [self.view bounds].size.height);
     
    /*
    
    if (self.interfaceOrientation == UIDeviceOrientationLandscapeLeft 
		|| self.interfaceOrientation == UIDeviceOrientationLandscapeRight)
	{
		//[m_dataMinorView drawLayout:LANDSCAPE_VIEW useFullScreen:self.m_isFullScreen];
	} 
	else if (self.interfaceOrientation == UIDeviceOrientationPortrait
			 || self.interfaceOrientation == UIDeviceOrientationPortraitUpsideDown)
	{
		//[m_dataMinorView drawLayout:PORTRAIT_VIEW useFullScreen:self.m_isFullScreen];
	}
     */
}


#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/

- (void) openLeftPanelView {
    iStateView = MAINVIEW_SHOW_LEFTPANEL;
    // Show left panel view
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.4];
    
    viewMainView.frame = CGRectMake(LEFTPANEL_WIDTH, 
                                    0, 
                                    [self.view bounds].size.width, 
                                    [self.view bounds].size.height);
    
    [UIView commitAnimations];	
    
    [viewMainView addGestureRecognizer:singleTap];

}

- (IBAction) btnLeftPanelClick {
    if (iStateView == MAINVIEW_NORMAL)
    {
        [self openLeftPanelView];
    }
}

- (void) handleSingleTap:(UIGestureRecognizer *) recognizer
{
	[self closeLeftPanelView];
}

#pragma mark - LeftPanel delegate methods

- (void) closeLeftPanelView {
    if (iStateView != MAINVIEW_SHOW_LEFTPANEL_FULL) {
        iStateView = MAINVIEW_NORMAL;
        // User do nothing, just close leftpanel view
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.4];
        
        viewMainView.frame = CGRectMake(0, 
                                        0, 
                                        [self.view bounds].size.width, 
                                        [self.view bounds].size.height);
        
        
        [UIView commitAnimations];
        
        [viewMainView removeGestureRecognizer:singleTap];
    }
    
}

- (void) openLeftPanelFullScreen {
    iStateView = MAINVIEW_SHOW_LEFTPANEL_FULL;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.2];
    
    viewMainView.frame = CGRectMake([self.view bounds].size.width, 
                                    0, 
                                    [self.view bounds].size.width, 
                                    [self.view bounds].size.height);
    
    viewLeftPanel.frame = CGRectMake(0, 0, [self.view bounds].size.width, [self.view bounds].size.height);
    
    [UIView commitAnimations];
    
    
	
    // Display search result data
    // ...
}

- (void) closeLeftPanelFullScreen {
    iStateView = MAINVIEW_SHOW_LEFTPANEL;
    [UIView beginAnimations:nil context:nil];
    
    [UIView animateWithDuration:0.2
                     animations:^ {
                         viewMainView.frame = CGRectMake(LEFTPANEL_WIDTH, 
                                                         0, 
                                                         [self.view bounds].size.width, 
                                                         [self.view bounds].size.height);
                         viewLeftPanel.frame = CGRectMake(0, 0, LEFTPANEL_WIDTH, [self.view bounds].size.height);
                         
                         // Over come bug of UISearchBar not animation
                         CGRect newBounds = viewLeftPanel.searchBar.frame;
                         newBounds.size.width = LEFTPANEL_WIDTH; 
                         viewLeftPanel.searchBar.frame = newBounds;
                         [viewLeftPanel.searchBar layoutSubviews];
                     }];

    [UIView commitAnimations];
   
        
    // Restore original left panel state
    // ...
}

- (void) changeFromView:(NSInteger) _iCurrentView toNewView:(NSInteger) _iNewView {
    // User click on row, and change to display another view (blog, album, activity, ...)
    // ...
    [viewActivity viewWillDisappear:YES];
    [viewActivity.view removeFromSuperview];
    
    NSString *strStoryboardIden;
    switch (_iNewView) {
        case 2: {
            strStoryboardIden = [NSString stringWithFormat:@"FeedActivity"];
            break;
        }
        
        case 8: {
            strStoryboardIden = [NSString stringWithFormat:@"AlbumModule"];
            break;
        }
        case 9: {
            strStoryboardIden = [NSString stringWithFormat:@"BlogModule"];
            break;
        }
        default:
            break;
    }
    
    // Init first screen, activity view
    ActivitiesViewController *controllerView = [self.storyboard instantiateViewControllerWithIdentifier:strStoryboardIden];
    controllerView.view.frame = CGRectMake(0, 0, viewMainContent.frame.size.width, viewMainContent.frame.size.height);
    // controllerView.delegate = self;
    viewActivity = controllerView;
    [viewMainContent insertSubview:viewActivity.view atIndex:0];

    // update new view index
    iCurrentView = _iNewView;
    [viewLeftPanel setCurrentView:iCurrentView];
    [self closeLeftPanelView];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    iCurrentView = LEFTVIEW_MAIN;
    
    // Init for leftpanel
    viewLeftPanel = [[LeftPanelView alloc] initWithFrame:CGRectMake(0, 0, LEFTPANEL_WIDTH, [self.view bounds].size.height)];
    viewLeftPanel.delegate = self;
    [self.view addSubview:viewLeftPanel];
    
    // Init value for LeftPanelView
    // viewLeftPanel.frame = CGRectMake(0, 0, LEFTPANEL_WIDTH, [self.view bounds].size.height);
    
    [viewLeftPanel setLoginState:loginState];
    [viewLeftPanel setCurrentView:iCurrentView];
    //viewLeftPanel.hidden = YES;
    
    // Header view
    [self.view bringSubviewToFront:viewMainView];
    [headerView setBackgroundColor:[[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"bkg_header.png"]]];
    
    singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    isDraging = NO;
    
    // Init first screen, activity view
    ActivitiesViewController *controllerView = [self.storyboard instantiateViewControllerWithIdentifier:@"FeedActivity"];
    controllerView.view.frame = CGRectMake(0, 0, viewMainContent.frame.size.width, viewMainContent.frame.size.height);
    // controllerView.delegate = self;
    viewActivity = controllerView;			
    [viewMainContent insertSubview:viewActivity.view atIndex:0];
}

#pragma mark Handle touch and drap move

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    
    CGPoint tappedPosition = [[touches anyObject] locationInView:self.view];
    xPosTouch = tappedPosition.x;
}

- (void) touchesMoved: (NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesMoved:touches withEvent:event];
    CGPoint tappedPosition = [[touches anyObject] locationInView:self.view];
    NSInteger xPos = tappedPosition.x;
    NSInteger iDistance = xPos - xPosTouch;
    isDraging = YES;
    if (iStateView == MAINVIEW_NORMAL) {
        if (iDistance > 0 && iDistance <= LEFTPANEL_WIDTH) {
            iCurrentDragPos = [[touches anyObject] previousLocationInView:self.view].x;
            
            viewMainView.frame = CGRectMake(iDistance, 
                                            0, 
                                            [self.view bounds].size.width, 
                                            [self.view bounds].size.height);
            
            
            
        }
    }
    else if (iStateView == MAINVIEW_SHOW_LEFTPANEL) {
        if (iDistance < 0 && iDistance >= -LEFTPANEL_WIDTH) {
            iCurrentDragPos = [[touches anyObject] previousLocationInView:self.view].x;
            viewMainView.frame = CGRectMake(LEFTPANEL_WIDTH + iDistance, 
                                            0, 
                                            [self.view bounds].size.width, 
                                            [self.view bounds].size.height);
            
        }
    }
    
}

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    if (isDraging) {
        CGPoint tappedPosition = [[touches anyObject] locationInView:self.view];
        NSInteger xPos = tappedPosition.x;
        if (xPos > iCurrentDragPos) {
            // open left panel
            [self openLeftPanelView];
        }
        else { //if (xPos < iCurrentDragPos) {
            // Close left panel view
            [self closeLeftPanelView];
        }
    }
    isDraging = NO;
}


- (void)viewDidUnload
{
    [self setHeaderView:nil];
    [self setBtnLeftPanel:nil];
    [self setViewMainView:nil];
    [self setViewMainContent:nil];
    [self setViewLeftPanel:nil];
    [self setViewActivity:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    // return (interfaceOrientation == UIInterfaceOrientationPortrait);
    return NO;
}

@end
